package com.joysuch.wwyt.datadump.biz.processor;

import cn.zlg.common.datadump.annotation.DataDumpEntity;
import cn.zlg.common.datadump.processor.BaseImportEntityProcessor;
import com.joysuch.wwyt.bp.entity.contractor.BpContractor;
import com.joysuch.wwyt.bp.entity.contractor.BpContractorStaff;
import com.joysuch.wwyt.bp.entity.contractor.dsl.QBpContractorStaff;
import com.joysuch.wwyt.bp.enums.DataStateTypes;
import com.joysuch.wwyt.core.entity.dsl.QBaseUser;
import com.joysuch.wwyt.datadump.biz.model.BpContractorDumpBean;
import com.joysuch.wwyt.datadump.biz.model.BpContractorStaffDumpBean;
import com.joysuch.wwyt.util.Validators;
import com.mysema.commons.lang.Assert;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.SimpleExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BpContractorStaffImportProcessor extends BaseImportEntityProcessor<BpContractorStaffDumpBean, BpContractorStaff> {

    @Autowired
    JPAQueryFactory factory;

    /**
     * ..承包商人员导入时 定位卡和门禁卡要做唯一性判断 人员和不同承包商单位的承包商人员,定位卡和门禁卡都不能一样
     *
     * @param origin
     * @param entity
     * @param annotation
     * @return
     */
    @Override
    public BpContractorStaff processBeforePersist(BpContractorStaffDumpBean origin, BpContractorStaff entity, DataDumpEntity annotation, boolean override) {
        entity.setState(DataStateTypes.EFFECTIVE.getState());
        if (origin.getSn() != null) {
            if (!Validators.validateMac(origin.getSn())) {
                throw new IllegalArgumentException("定位卡号格式不正确");
            }
            cardNumberNotExists("定位", origin.getSn(), entity.getId());
        }
        if (origin.getCardNumber() != null) {
            cardNumberNotExists("门禁", origin.getCardNumber(), entity.getId());
        }
        return entity;
    }

    void cardNumberNotExists(String prefix, String no, Long id) {
        QBpContractorStaff qs = QBpContractorStaff.bpContractorStaff;
        QBaseUser qu = QBaseUser.baseUser;
        // 承包商已经存在
        long count = factory.select(qs.count()).from(qs).
                where(
                        qs.sn.eq(no).or(qs.cardNumber.eq(no)),
                        stateOrNull(qs.state, DataStateTypes.EFFECTIVE.getState()),
                        id == null ? qs.isNotNull() : qs.id.ne(id) // 排除本人
                ).fetchCount();
        Assert.isTrue(count == 0, prefix + "卡号:" + no + "在承包商人员中已存在");

        // 检查人员
        count = factory.select(qu.count()).from(qu).where(qu.cardNumber.eq(no).or(qu.sn.eq(no)), qu.state.ne(DataStateTypes.DELETE.getState()).or(qu.state.isNull())).fetchCount();
        Assert.isTrue(count == 0, prefix + "卡号:" + no + "在人员中已存在");

    }


    private Predicate stateOrNull(SimpleExpression path, Integer value) {
        return path.eq(value).or(path.isNull());
    }

}
